﻿using Gx.Common;
using Gx.Common.Core;
using Gx.Dal.Manage;
using Gx.Dal.Shared;
using Gx.Model;
using Gx.Model.Entity;
using Gx.Model.Enums;
using Gx.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web;


namespace Gx.Bll.Manage
{
    public class LKZeroWarehouseContractBll
    {
        protected LKAttachmentBll attachmentBll = new LKAttachmentBll();
        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedList<LKZeroWarehouseContract> GetLKZeroWarehouseContractPageList(LKZeroWarehouseContractInput input)
        {
            LKZeroWarehouseContractDal dal = new LKZeroWarehouseContractDal();
            return dal.GetLKZeroWarehouseContractPageList(input);
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public List<LKZeroWarehouseContract> GetLKZeroWarehouseContracts()
        {
            LKZeroWarehouseContractDal dal = new LKZeroWarehouseContractDal();
            return dal.GetAll().ToList();
        }

        /// <summary>
        /// 新增零仓合同
        /// </summary>
        /// <param name="contract"></param>
        /// <returns></returns>
        public ReturnModel AddLKZeroWarehouseContract(LKZeroWarehouseContractDto contract)
        {
            var lKZeroWarehouseContract = contract.LKZeroWarehouseContract;
            var costList = contract.CostList;
            LKZeroWarehouseContractDal dal = new LKZeroWarehouseContractDal();
            LKIncidentalsDal lKIncidentalsDal = new LKIncidentalsDal();
            //var any = dal.AnyName(lKZeroWarehouseContract.LevelName);
            //if (any)
            //{
            //    return new ReturnModel { Success = false, Msg = "名称已存在" };
            //}
            //合同编号规则：L240520002
            //L+年月日+三位流水号
            string maxCode = dal.GetMaxLKZeroWarehouseContractCode();
            string code = "L" + DateTime.Now.ToString("yyMMdd") + "001";
            if (!string.IsNullOrWhiteSpace(maxCode))
            {
                var maxMonth = maxCode.Substring(2, 2);
                var nowMonth = DateTime.Now.ToString("MM");
                if (maxMonth == nowMonth)
                {
                    int num = Convert.ToInt32(maxCode); //Convert.ToInt32(maxCode.Substring(7, 3));
                    num++;
                    code = "L" + num.ToString();//DateTime.Now.ToString("yyMMdd") + num.ToString().PadLeft(3, '0');
                }
            }
            lKZeroWarehouseContract.ContractNo = code;

            lKZeroWarehouseContract.CreateTime = DateTime.Now;
            lKZeroWarehouseContract.CreateUserId = LoginHelper.GetUserId();
            lKZeroWarehouseContract.CreateUser = LoginHelper.UserName();
            lKZeroWarehouseContract.CompanyId = UserContext.CompanyId;
            lKZeroWarehouseContract.IsValid = true;
            //var result = dal.Insert(lKZeroWarehouseContract);

            if (costList != null && costList.Any())
            {
                costList.ForEach(item =>
                {
                    //item.ContractId = lKZeroWarehouseContract.Id;
                    item.ContractType = (int)BillType.ZeroWarehouseContract;
                    item.ContractNo = code;
                    item.CreateUser = LoginHelper.UserName();
                    item.CreateUserId = LoginHelper.GetUserId();
                });
                //lKIncidentalsDal.Insert(costList);
            }

            var result = dal.AddLKZeroWarehouseContract(lKZeroWarehouseContract, costList);

            if (result && contract.AttachmentId > 0)
            {
                attachmentBll.SaveLKAttachment(new LKAttachment
                {
                    Id = contract.AttachmentId,
                    BillNo = lKZeroWarehouseContract.ContractNo,
                    BillType = (int)BillTypeTemplate.ZeroWarehouse,
                });
            }

            return new ReturnModel { Success = result, Msg = result ? "新增成功" : "新增失败" };
        }

        /// <summary>
        /// 编辑零仓合同
        /// </summary>
        /// <param name="contract"></param>
        /// <returns></returns>
        public bool EditLKZeroWarehouseContract(LKZeroWarehouseContractDto contract)
        {
            if (contract == null) return false;
            var lKZeroWarehouseContract = contract.LKZeroWarehouseContract;
            var costList = contract.CostList;
            LKZeroWarehouseContractDal dal = new LKZeroWarehouseContractDal();
            var cus = dal.Get(lKZeroWarehouseContract.Id);
            if (cus == null)
            {
                return false;
            }
            if (cus.CompanyId != UserContext.CompanyId) return false;
            lKZeroWarehouseContract.ContractNo = cus.ContractNo;
            lKZeroWarehouseContract.CreateTime = cus.CreateTime;
            lKZeroWarehouseContract.CreateUserId = cus.CreateUserId;
            lKZeroWarehouseContract.CreateUser = cus.CreateUser;
            lKZeroWarehouseContract.ModifyUserId = LoginHelper.GetUserId();
            lKZeroWarehouseContract.ModifyUser = LoginHelper.UserName();
            lKZeroWarehouseContract.ModifyTime = DateTime.Now;
            lKZeroWarehouseContract.CompanyId = UserContext.CompanyId;

            var result = dal.EditLKZeroWarehouseContract(lKZeroWarehouseContract, costList, contract.DeleteIds);

            if (result && contract.AttachmentId > 0)
            {
                attachmentBll.DeleteLKAttachment(lKZeroWarehouseContract.ContractNo);
                attachmentBll.SaveLKAttachment(new LKAttachment
                {
                    Id = contract.AttachmentId,
                    BillNo = lKZeroWarehouseContract.ContractNo,
                    BillType = (int)BillTypeTemplate.ZeroWarehouse,
                });
            }

            return result;
        }

        /// <summary>
        /// 删除零仓合同
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnModel DeleteLKZeroWarehouseContract(int id)
        {
            LKZeroWarehouseContractDal dal = new LKZeroWarehouseContractDal();
            LKWarehouseEntryDal lKWarehouseEntryDal = new LKWarehouseEntryDal();
            var contract = dal.Get(id);
            if (contract == null) return new ReturnModel { Success = false, Msg = "合同不存在" };
            if (contract.CompanyId != UserContext.CompanyId) return new ReturnModel { Success = false, Msg = "无权限" };
            var entry = lKWarehouseEntryDal.GetListByWhere("ContractNo=@ContractNo", new { contract.ContractNo }).ToList();
            if (entry.Any())
            {
                return new ReturnModel { Success = false, Msg = "该合同已有入库单，不能删除" };
            }

            var result= dal.DeleteLKZeroWarehouseContract(id);
            if (result)
            {
                attachmentBll.DeleteLKAttachment(contract.ContractNo);
            }
            return new ReturnModel { Success = result, Msg = result ? "删除成功" : "删除失败" };
        }

        /// <summary>
        /// 获取零仓合同
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LKZeroWarehouseContractDto GetLKZeroWarehouseContractById(int id)
        {
            LKZeroWarehouseContractDal dal = new LKZeroWarehouseContractDal();
            var contract = dal.Get(id);

            if (contract.CompanyId != UserContext.CompanyId) 
                return new LKZeroWarehouseContractDto();

            LKIncidentalsDal lKIncidentalsDal = new LKIncidentalsDal();
            var costList = lKIncidentalsDal.GetLKIncidentalsListByContract(id, (int)BillType.ZeroWarehouseContract);

            var attachment = attachmentBll.GetLKAttachmentView(contract.ContractNo);
            return new LKZeroWarehouseContractDto { LKZeroWarehouseContract = contract, CostList = costList, FilePath = attachment?.AttachmentName, FileName = attachment?.OriginalName };
        }
    }
}

